﻿using System;
using System.Runtime.Serialization;

namespace Modbus
{
	[Serializable]
	public class ModbusSlaveException : ModbusException
	{
		private readonly byte functionCode;
		private readonly byte exceptionCode;
		private string description;

		#region ( Constructors )

		public ModbusSlaveException()
			: base(ModbusError.SlaveException)
		{
		}

		public ModbusSlaveException(byte functionCode, byte exceptionCode)
			: base(ModbusError.SlaveException)
		{
			this.functionCode = functionCode;
			this.exceptionCode = exceptionCode;
		}

		protected ModbusSlaveException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
			this.functionCode = info.GetByte(SR.ModbusSlaveException_FunctionCode);
			this.exceptionCode = info.GetByte(SR.ModbusSlaveException_ExceptionCode);
		}

		#endregion

		private static string GetExceptionDescription(byte exceptionCode)
		{
			// TODO: Insert implementation.
			return String.Empty; // stub.
		}

		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			base.GetObjectData(info, context);

			info.AddValue(SR.ModbusSlaveException_FunctionCode, this.functionCode, typeof(byte));
			info.AddValue(SR.ModbusSlaveException_ExceptionCode, this.exceptionCode, typeof(byte));
		}

		public byte FunctionCode
		{
			get { return this.functionCode; }
		}

		public byte ExceptionCode
		{
			get { return this.exceptionCode; }
		}

		public override string Message
		{
			get
			{
				if (this.description == null)
				{
					this.description = GetExceptionDescription(this.exceptionCode);
				}

				return (base.Message + Environment.NewLine + this.description);
			}
		}
	}
}
